var urlParam;//获取界面调用传入的参数
var page ;//全局对象
var submitFlag = false;
//初始化加载查询数据
cmp.ready(function () {
//初始化传入参数
    _initParamData();
    //从数据库中取数据
    initPageData();
    cmp.i18n.init(_templateApprovePath+"/i18n/", "templateApproveResources", function() {
        initLayout();
    },templateApproveBuildVersion);
    //初始化事件
    initEvent();
});
function _initParamData() {

    urlParam = cmp.href.getParam() || {};

    if(cmp.isEmptyObject(urlParam)) {
        //从utils中获取参数
        urlParam = templateApproveUtils.getHrefQuery();
    }

}
/****************************** 监听返回事件(放到最前头)  ******************************/
function initPageBack() {

    //cmp控制返回
    cmp.backbutton();
    cmp.backbutton.push(_isClearGoBack);
}
//初始化事件
function initEvent() {
    //派发流程模板点击打开事件
    var agreeBackBtn = document.getElementById("agree");
    agreeBackBtn.addEventListener("tap", _dealAgree);

    var disAgreeBackBtn = document.getElementById("disAgree");
    disAgreeBackBtn.addEventListener("tap", _dealDisAgree);

}
function _dealDisAgree(){

    _formLoadCheck({
        checkCallback : function(ret){
            if(ret == true && submitFlag == false){
                submitFlag = true;
                _dealtemplateApprove(1);
            }
        }
    });
}
//提交请求
function _dealtemplateApprove(adoptType){
    var paramData= {
        Adopt:adoptType, // 是否同意，或者通过  0 为默认通过 1为不通过
        id: document.getElementById("approveId" ).value,            //审批id
        opinion: document.getElementById("approveOpinion" ).value ,   // 审批意见
        affairId:document.getElementById("affairId" ).value  //当前审批的事项affairID
    }

    $s.templateApprove.dealWithApproveWorkFlowInfo({},paramData, {
        success : function(result) {
            cmp.dialog.loading(false);
            /** 当前Affair状态校验 */
            if(result["status"] == true){
                //触发平台事件，用于刷新列表数据
                cmp.webViewListener.fire({
                    type: "com.seeyon.m3.ListRefresh",
                    data: {type: 'update'}
                });
                _goBack();
                return;
            }else{
                if(result["error_msg"] && result["error_msg"]!="") {
                    _alert(result["error_msg"], function() {
                        _goBack();
                    });
                    return;
                }
            }

            //关闭并刷新-待办栏目页
        },
        error : function(result){
            //处理异常
            templateApproveUtils.dealError(result);
        }
    });
}
//支持原样表单，多一层验证
function _dealAgree(){
    _formLoadCheck({
        checkCallback : function(ret){
            if(ret == true && submitFlag == false){
                submitFlag = true;
                _dealtemplateApprove(0);
            }
        }
    });
}

//原表单预提交处理
var _violenceClickFlag = false;
function _formLoadCheck(xParams){

    if(_violenceClickFlag){
        //暴力点击
        return;
    }

    _violenceClickFlag = true;

    var checkCallback;

    checkCallback = function(ckRet){
        xParams.checkCallback(ckRet);
        _violenceClickFlag = false;
    }

    //直接提交
    checkCallback(true);
}

//跳转到流程模板界面
function gotoFlowtemplateHtml() {
    page.operate = "conferee";
    cmp.href.next(_templateApprovePath + "/html/flowtemplate.html"+templateApproveBuildVersion, page);
}
/**
 * 后台数据装载到页面缓存page对象中
 */
function initPageData() {
    var paramAffairId = -1;
    if (urlParam["affairId"] != undefined && urlParam["affairId"]!="" && urlParam["affairId"] != "null") {
        paramAffairId = urlParam["affairId"]
    }
    var paramObjectId = (!urlParam["objectId"]||urlParam["objectId"]=="") ? -1 : urlParam["objectId"];
    var paramFormId = (!urlParam["formId"]||urlParam["formId"]=="") ? -1 : urlParam["formId"];
    var paramTemplateId = (!urlParam["templateId"]||urlParam["templateId"]=="") ? -1 : urlParam["templateId"];
    var paramData = {
        "affairId":paramAffairId,
        "objectId":paramObjectId,
        "templateId":paramTemplateId,
        "formId":paramFormId};

    cmp.dialog.loading();
    $s.templateApprove.findDealWithInfo({},paramData, {
        success : function(result) {
            cmp.dialog.loading(false);
            /** 当前Affair状态校验 */
            if(result["error_msg"] && result["error_msg"]!="") {
                _alert(result["error_msg"], function() {
                    _goBack();
                });
                return;
            }

            page = result;

            document.getElementById("affairId").value = result.message.affairId;
            document.getElementById("approveId").value = result.message.approveId;
            //事项标题
            document.getElementById("title").innerHTML = result.message.subject;

            //流程模板名
            document.getElementById("flowtemplateName").innerHTML =   result.message.ctpTemplate.subject;
            //版本号
            document.getElementById("versionNumber").innerHTML= result.message.templateApprovePO.version;
            //发布时间
            document.getElementById("releaseTime").innerHTML = result.message.templateApprovePO.releaseTime;

            //申请说明
            document.getElementById("remark").innerHTML= result.message.templateApprovePO.remark;

            //意见信息
            var approveDetails = result.message.ApproveDetails;
            var size = approveDetails.length;
            if(size>0){
                var titleTpl = document.querySelector("#opinionListModule").innerHTML;
                document.querySelector("#opinionList").innerHTML = cmp.tpl(titleTpl, approveDetails);
            }
            //如果是已经处理过那么久设置为不可处理
            if(result.message.state == 4 || result.message.state == "4"){
                document.getElementById("approveOpinion").setAttribute("disabled", true);
                document.getElementById("disAgree").setAttribute("disabled", true);
                document.getElementById("agree").setAttribute("disabled", true);

                _alert(cmp.i18n("templateapprove.page.flow.template.back"), function() {
                    _goBack();
                });
                return;
            }
            //初始化页面
        },
        error : function(result){
            //处理异常
            templateApproveUtils.dealError(result);
        }
    });
}


function initLayout(){
    var totalHeight =  document.body.offsetHeight;
    var contentheight =  document.getElementById("body_content_div").offsetHeight;
    var remainheight= totalHeight - contentheight-38;
    if(remainheight>0){
        //重新计算
        remainheight = remainheight;
        document.getElementById("opinionList").style.height = remainheight+"px";
    }


}
function _alert(message, completeCallback, title, buttonLabel) {
    cmp.notification.alert(message, completeCallback, title, cmp.i18n("templateapprove.page.flow.template.yes"));
}
function _goBack() {
    cmp.href.back();
}

 function createOpinion(pDatas){
    var result=new Array();
    result.push("\r\n");

    var rightWidth = "";
    if(pDatas.width && pDatas.width != "100%"){
        rightWidth = "width:" + (pDatas.width - 70) + "px";
    }
    for(var i = 0,len=pDatas.comments.length; i < len; i++){
        var comment = pDatas.comments[i];
        var _replyColUser="replyColUser_"+i;



        result.push("<li class=\"attach-lisy-li flexbox\">\r\n");
        result.push(" <div class=\"form-attitude\">\r\n");
        result.push("    <div class=\"form-attitude-line\"></div>\r\n");
        result.push("    ");
        result.push("\r\n");
        var attiIconClass = "";
        var attiColor = "";
        var attitudeCode = comment.attitudeCode;
        switch(attitudeCode){
            case "collaboration.dealAttitude.agree":
                attiIconClass = "m3-icon-agree";
                attiColor = "agree";
                break;
            case "collaboration.dealAttitude.haveRead":
                attiIconClass = "m3-icon-read";
                break;
            case "collaboration.dealAttitude.disagree":
                attiIconClass = "m3-icon-disagree";
                attiColor = "disagree";
                break;
            case "collaboration.dealAttitude.termination":
                attiIconClass = "m3-icon-termination";
                attiColor = "termination";
                break;
            default:
                attiIconClass = "m3-icon-read";
                break;
        }


        result.push("    <div class=\"form-attitude-wrap "+s3utils.c2vb(attiColor)+"\"><span class=\""+s3utils.c2vb(attiIconClass)+"\"></span>");
        if(comment.attitude){
            result.push("<br/><span class=\"font_14\">"+s3utils.c2hb(comment.attitude)+"</span>");
        }
        result.push("  \r\n");
        result.push("    </div>\r\n");
        result.push(" </div>\r\n");
        result.push(" <div style=\""+s3utils.c2vb(rightWidth)+"\" class=\"opinion-wrap-div white flex-1 form-opinion\">\r\n");
        result.push("   <div class=\"user-info\">\r\n");
        result.push("      <div id=\""+s3utils.c2vb(_replyColUser)+"\">\r\n");
        result.push("      \t<img class=\"cmp-img-cache cmp-pull-left img_setting\" cmp-data=\""+s3utils.c2vb(comment.createId)+"\"/>\r\n");
        result.push("      </div>\r\n");
        result.push("      ");
        if(comment.action){
            result.push("<span class=\"states\">"+s3utils.c2hb(comment.action)+"</span>");
        }

        result.push("       <div class=\"user-name\">"+s3utils.c2hb(comment.createName)+"\r\n");
        result.push("           <span style=\"color:#ff0000;\">"+s3utils.c2hb(comment.agent)+"</span>\r\n");
        result.push("       </div>\r\n");
        result.push("   </div>\r\n");
        result.push("   <div class=\"opinion-div\" style=\"white-space:normal;word-break: break-word;word-wrap: break-word;\">\r\n");
        result.push("      ");
        if(comment.praiseToSummary){

            result.push("          <span class=\"cmp-icon m3-icon-support blue-color cmp-active\"></span>\r\n");
            result.push("       ");
        }

        result.push("       <div id=\"commentStyle\">\r\n");
        result.push("       ");
        result.push(comment.content)

        result.push("       </div>\r\n");
        result.push("   </div>\r\n");
        result.push("<ul id=\""+s3utils.c2vb(pDatas.containerId)+"_commentAttr"+s3utils.c2vb(comment.id)+"\" class=\"cmp-list-content cmp-accessory-content margin_top-1\"></ul>\r\n");
        result.push("\r\n");
        var m1InfoHTML = "", opinionDivHeight = "", m1InfoLineheight="";
        if(comment.m1Info){
            m1InfoHTML = '<br/><span>' + s3utils.c2hb(comment.m1Info) + '</span>';
            opinionDivHeight = "height:auto;";
            m1InfoLineheight = "line-height:1.5;"
        }


        result.push("<div class=\"opinion-time-div\" style=\""+s3utils.c2vb(opinionDivHeight)+"\">\r\n");
        result.push("        <div class=\"zan-div\">\r\n");
        result.push("           ");
        if(pDatas.canPraise) {

            result.push("               <span likeNum=\""+s3utils.c2vb(comment.praiseNumber)+"\" commentId=\""+s3utils.c2vb(comment.id)+"\" style=\"padding:0px 0px 5px 5px;height:100%;line-height:26px;\" class=\"cmp-icon comment_like_btn comment_like_btn_"+s3utils.c2vb(comment.id)+" ");
            if(comment.praiseToComment){
                result.push("m3-icon-support cmp-active");
            }else{
                result.push("m3-icon-support");
            }
            result.push("\"></span>\r\n");
            result.push("               <span class=\"comment_like_num_"+s3utils.c2vb(comment.id)+"\" style=\"margin:0px;");
            if(!pDatas.replyFlag){
                result.push(" padding-right:15px; ");
            }
            result.push(" ");
            if(comment.praiseToComment){
                result.push("color:#3AADFB;");
            }
            result.push("\">"+s3utils.c2hb(comment.praiseNumber)+"</span>\r\n");
            result.push("            ");
        }

        result.push("            ");
        if(pDatas.replyFlag){

            result.push("                <span commentId=\""+s3utils.c2vb(comment.id)+"\" style=\"padding: 0px 15px 0px 8px;height:100%;line-height:33px;\" class=\"cmp-icon m3-icon-revert-fill replay_btn\"></span>\r\n");
            result.push("            ");
        }
        result.push(" \r\n");
        result.push("        </div>\r\n");
        result.push("       <div class=\"opinion-time\">\r\n");
        result.push("           <p style=\""+s3utils.c2vb(m1InfoLineheight)+"\"><span>"+s3utils.c2hb(comment.createDate)+"</span>");
        result.push(m1InfoHTML)
        result.push("</p>\r\n");
        result.push("       </div>\r\n");
        result.push("</div>\r\n");
        result.push("\r\n");
        if(comment.subReplys && comment.subReplys.length > 0){


            result.push("<div class=\"comment-div\">\r\n");
            result.push(" <div class=\"comment-body\">\r\n");
            result.push("   \r\n");
            result.push("        ");
            result.push("\r\n");
            for(var j = 0; j < comment.subReplys.length; j++){
                var subComment = comment.subReplys[j];


                result.push("        <ul>\r\n");
                result.push("      <li>\r\n");
                result.push("          <p class=\"comment-p\">\r\n");
                result.push("          <span class=\"name-mark\"></span>\r\n");
                result.push("          \t"+s3utils.c2hb(subComment.createName)+"\r\n");
                result.push("          \t<span style=\"color:#ff0000;\">"+s3utils.c2hb(subComment.agent)+"</span>\r\n");
                result.push("          </p>\r\n");
                result.push("      </li>\r\n");
                result.push("      <li>\r\n");
                result.push("          <p class=\"comment\">");
                result.push(subComment.content)
                result.push("</p>\r\n");
                result.push("      </li>\r\n");
                result.push("      <li>\r\n");
                result.push("          <ul id=\""+s3utils.c2vb(pDatas.containerId)+"_subCommentAttr"+s3utils.c2vb(subComment.id)+"\" class=\"cmp-list-content cmp-accessory-content margin_top-1\"></ul>\r\n");
                result.push("      </li>\r\n");
                result.push("      <li>\r\n");
                result.push("          <p class=\"comment-t\">\r\n");
                result.push("              <span>"+s3utils.c2hb(subComment.createDate)+"</span>\r\n");
                result.push("              <span>"+s3utils.c2hb(subComment.m1Info)+"</span>\r\n");
                result.push("          </p>\r\n");
                result.push("      </li>\r\n");
                result.push("       </ul>\r\n");
                result.push("        ");
            }

            result.push("   </div>\r\n");
            result.push("</div>\r\n");
        }


        result.push("</div>\r\n");
        result.push("</li>\r\n");
    }

    return result.join("");
}
